package com.yix.study.tec.entity;

/**
 * 懒汉式单例模式
 *
 */
public class SingletonLazy {
    public static void main(String[] args) {
        President president = President.getInstance();
        president.getName();
        President president1 = President.getInstance();
        president1.getName();
        if(president1 == president){
            System.out.println("他们是同一人");
        }else {
            System.out.println("他们不是同一人");
        }
    }
}

class President{
    private static volatile President instance = null;//保证instance在所有线程同步

    //private防止外部实例合Presideng
    private President(){
        System.out.println("产生一个总统");
    }

    public static synchronized President getInstance(){
        //在getInstance方法上加同步
        if(instance == null){
            instance = new President();
        }else {
            System.out.println("已经有一个总统，不能产生新总统！");
        }
        return instance;
    }

    public void getName(){
        System.out.println("我是美国总统，普顿！");
    }
}
